from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet,GenericViewSet, ModelViewSet

import json

from books import serializer
from .serializer import BookSerializer
from books.models import BookInfo
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView





class Books(ViewSet):

    def list(self, request):
        print(request.query_params)
        books = BookInfo.objects.all()
        ser = BookSerializer(books, many=True)
        return Response(ser.data)

    def create(self, request):
        # data = request.body.decode()
        # data_dict = json.loads(data)
        data_dict = request.data
        # 验证数据
        ser = BookSerializer(data=data_dict)
        # 修改时
        # ser = BooksSerializer('查询集对象', data=data_dict)
        # 验证错误直接报错
        ser.is_valid(raise_exception=True)
        # 获取验证成功后的字段
        # print(ser.validated_data)
        # 保存书据 看序列类参数是否传递　决定创建还是更改
        ser.save()
        # 响应
        return Response(ser.data)
class Book(GenericViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer
    def list(self,request):
        books = self.get_queryset()
        ser = self.get_serializer(books,many=True)
        return Response(ser.data)
    def update(self, request, pk):
        data = request.data
        book = self.get_object()

        # 验证数据
        # ser = BooksSerializer(data=data_dict)
        # 修改时
        ser = self.get_serializer(book, data=data)
        # 验证错误直接报错
        ser.is_valid(raise_exception=True)
        # 获取验证成功后的字段
        # print(ser.validated_data)
        # 保存书据 看序列类参数是否传递　决定创建还是更改
        ser.save()
        # 响应
        return Response(ser.data)


class BooksMedolSet(ModelViewSet):
    # authentication_classes = (SessionAuthentication, BasicAuthentication)
    # permission_classes = (IsAuthenticated,)
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer
